import React, { Component } from 'react';

import { Card, Button, Table, Space, message, Modal, Input, Tree } from 'antd';

import { timeFormat } from '../../utils/toolKit';
import { reqRoleList, reqRoleAdd, reqRoleUpdate } from '../../api';
import menuList from '../../config/menuConfig';
import memory from '../../utils/memoryUtils';
import storage from '../../utils/storageUtils';

const TIMEFORMAT = 'yyyy-MM-dd hh:mm:ss';
/**
 * 角色管理
*/
export default class Role extends Component {

    state = {
        roles: [],
        loading: false,
        selectedRole: {},
        checkedKeys: [],
        createRoleVisible: false,
        permissionSettingVisible: false,
    }

    columns = [
        {
            title: '角色名称',
            dataIndex: 'name',
            width: '200px'
        },
        {
            title: '创建时间',
            dataIndex: 'create_time',
            width: '300px',
            render: record => timeFormat(record, TIMEFORMAT)
        },
        {
            title: '授权时间',
            dataIndex: 'auth_time',
            width: '300px',
            render: record => timeFormat(record, TIMEFORMAT)
        },
        {
            title: '授权人',
            dataIndex: 'auth_name',
            width: '200px'
        }
    ]

    async getRoleList() {
        this.setState({ loading: true });
        const res = await reqRoleList();

        if (res.status === 0) {
            const { data } = res;
            this.setState({ roles: data, loading: false });
        } else {
            message.error('获取角色列表失败！');
            this.setState({ loading: false });
        }
    }

    onRow(record) {
        return {
            onClick: () => {
                this.setState({
                    selectedRole: record,
                    disabled: false,
                    checkedKeys: record.menus
                })
            }
        }
    }

    handleCreateClick() {
        this.setState({
            createRoleVisible: !this.state.createRoleVisible
        })
    }

    handleManageClick() {
        this.setState(state => ({
            permissionSettingVisible: !this.state.permissionSettingVisible,
            checkedKeys: state.selectedRole.menus
        }))
    }

    handleCheck(checkedKeys) {
        this.setState({
            checkedKeys: checkedKeys
        });
    }

    async handleManageOk() {
        const { selectedRole, checkedKeys } = this.state;

        const res = await reqRoleUpdate({
            _id: selectedRole._id,
            menus: checkedKeys,
            auth_time: Date.now(),
            auth_name: memory.user.username
        });

        if (res.status === 0) {
            message.success('更新角色权限成功！');

            // 如果当前更新的是当前角色的权限，则强制退出登录
            if (selectedRole._id === memory.user.role_id) {
                storage.delUser();
                memory.user = {};
                this.props.history.replace('/login');
                message.warn('当前用户角色权限修改了，请重新登录！')
            } else {
                const roles = [...this.state.roles];
                const { data } = res;

                roles[roles.findIndex(role => role._id === data._id)] = data;
                this.setState({ roles, permissionSettingVisible: false });
            }
        } else {
            message.error(res.msg);
        }
    }

    roleNameRef = React.createRef()
    async handleCreateOk() {
        const roleName = this.roleNameRef.current.state.value || '';
        if (!roleName.trim()) {
            message.error('角色名不能为空！')
        } else {
            const res = await reqRoleAdd(roleName.trim());

            if (res.status === 0) {
                const { roles } = this.state;
                const { data } = res;
                message.success('添加角色成功！');
                this.setState({
                    roles: [...roles, data],
                    createRoleVisible: false
                })
                this.roleNameRef.current.state.value = '';
            } else {
                message.error(res.msg)
            }
        }
    }

    handleCreateCancel() {
        this.setState({
            createRoleVisible: !this.state.createRoleVisible
        })
        this.roleNameRef.current.state.value = '';
    }

    handleManageCancel() {
        this.setState({
            permissionSettingVisible: !this.state.permissionSettingVisible
        })
    }

    componentDidMount() {
        this.getRoleList();
    }

    render() {
        const { roles, loading, selectedRole, createRoleVisible, permissionSettingVisible, checkedKeys } = this.state;

        const title = (
            <Space>
                <Button
                    type="primary"
                    onClick={() => this.handleCreateClick()}
                >
                    创建角色
                </Button>
                <Modal
                    title="创建角色"
                    visible={createRoleVisible}
                    onOk={() => this.handleCreateOk()}
                    onCancel={() => this.handleCreateCancel()}
                >
                    <Input autoFocus placeholder="请输入角色名" ref={this.roleNameRef} />
                </Modal>
                <Button
                    type="primary"
                    onClick={() => this.handleManageClick()}
                    disabled={!selectedRole._id}

                >
                    设置角色权限
                </Button>
                <Modal
                    title="设置角色权限"
                    visible={permissionSettingVisible}
                    onOk={() => this.handleManageOk()}
                    onCancel={() => this.handleManageCancel()}
                >
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: '30px' }}>
                        <span style={{ flexShrink: '0' }}>角色名称：</span>
                        <Input disabled value={selectedRole.name}></Input>
                    </div>
                    <Tree
                        checkable
                        defaultExpandAll
                        checkedKeys={checkedKeys}
                        selectable={false}
                        onCheck={(checkedKeys) => this.handleCheck(checkedKeys)}
                        treeData={[{ title: '平台权限', key: '/', children: menuList }]}
                    />
                </Modal>
            </Space>
        )

        return (
            <Card title={title} >
                <Table
                    columns={this.columns}
                    dataSource={roles}
                    bordered
                    loading={loading}
                    scroll={{ y: 450 }}
                    rowKey="_id"
                    rowSelection={{
                        type: 'radio',
                        columnWidth: '60px',
                        selectedRowKeys: [selectedRole._id],
                        onSelect: record => this.setState({ selectedRole: record })
                    }}
                    onRow={record => this.onRow(record)}
                />
            </Card>
        )
    }
}
